package org.nacos.consumer.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.nacos.consumer.entity.OrderDTO;
import org.nacos.consumer.mapper.OrderMapper;
import org.nacos.consumer.service.IOrderService;
import org.nacos.consumer.service.feign.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderDTO> implements IOrderService {

	/**
	 * Seata 服务端部署
	 * 1. 修改 \conf\application.yml 配置文件，修改配置中心和注册中心(nacos)
	 * 2. 配置 \script\config-center\config.txt 到 nacos 配置中心，store.db 改为 seata 使用的配置库；
	 * 若缺少配置 service.vgroupMapping.application-system-group=default，需要手动添加
	 * 3. 执行配置表初始化sql，脚本路径 \script\server\db
	 * 4. 若使用 AT 模式，业务库需要增加配置表 undo_log，可在 github 获取对应脚本
	 */

	@Autowired
    private DiscoveryClient discoveryClient;

	@Autowired
    private ProductService productService;

	@Autowired
	@Qualifier("restTemplate")
    private RestTemplate restTemplate;

	@SuppressWarnings("unchecked")
	@Override
	@GlobalTransactional
	public Map<String, Object> getService(Integer type) {
		
    	this.removeById(1);
    	
    	Map<String, Object> map = new HashMap<String, Object>();
    	if (type%4 == 1) {
    		// 方式一 RestTemplate 调用
    		map = restTemplate.getForObject("http://127.0.0.1:8071/product/" + type, Map.class);
    		log.info("RestTemplate {}", map);
    	} else if (type%4 == 2) {
    		// 方式二 Nacos 配合 RestTemplate 调用
    		ServiceInstance serviceInstance =
                    discoveryClient.getInstances("service-provider")
                    .stream().findAny().get();
            String url = String.format("http://%s:%s/product/%d", serviceInstance.getHost(), 
            		serviceInstance.getPort(), type);
    		map = restTemplate.getForObject(url, Map.class);
    		log.info("Nacos + RestTemplate {}", map);
    	} else if (type%4 == 3) {
    		// 方式三 openFeign 调用
    		map = productService.queryProductInfo(type);
    		log.info("openFeign {}", map);
    	} else {
    		map.put("err_msg", "Not supported type: " + type);
    		log.info("Not supported type: {}", type);
    	}
    	// 分布式事务测试用
        if (type < 4) {
            throw new RuntimeException("异常，分布式事务测试！");
        }
		return map;
	}

}
